<?php
namespace App\Http\Controllers\Weixin;

use App\Http\Controllers\Controller;
use Session;
/**
 * 微信授权
 */
 
class WxAuthController extends Controller {
	
	public function __construct(){
		header("Content-type:text/html;charset=utf-8");
		//微信配置信息
		require_once(app_path().'/Library/Wxpay/lib/WxPayConfig.php');
		
		date_default_timezone_set('Asia/Shanghai');
    }
	
	function auth(){
		if (!isset($_GET["code"])){
			echo "No code！";exit;
		}
		$userinfo = $this->getUserInfo(\WxPayConfig::APPID,\WxPayConfig::APPSECRET,$_GET["code"]);
		
		Session::put('userinfo', $userinfo);
		$url = '/'.urldecode($_GET['state']);
		return redirect()->to($url);
	}
	
	/**
	 * 获取用户信息
	 */
	
	function getUserInfo($appid,$appsecret,$code){
		$token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
		$token_info = $this->https_request($token_url);

		$access_token = $token_info['access_token']; 
		$openid = $token_info['openid'];
		
		//检验 Access_Token 是否有效
		$check_accesstoken_url = "https://api.weixin.qq.com/sns/auth?access_token=$access_token&openid=$openid";
		$check_result = $this->https_request($check_accesstoken_url);

		$userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN"; 
		$user_info = $this->https_request($userinfo_url);

		//return $token_info['openid'];
		return $user_info;
	}

	/**
	* php转发post函数
	*/
	function https_request($url){
		$curl = curl_init();  //初始化一个cURL会话
		//设置请求选项, 包括具体的url
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);  //禁用后cURL将终止从服务端进行验证
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($curl,CURLOPT_HEADER,0); //??
		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10); //??
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);		
		$response = curl_exec($curl);  
		curl_close($curl);
		$jsoninfo = json_decode($response,true); 
		return $jsoninfo;
	}
}